package com.hfb.mashibing.alip8.juc.c018_00_AtomicXXX;


import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

public class T02_AtomicVsSynchronizedLongAdder {
    // 效率从高到低:LongAdder>Atomic>synchronized
    static AtomicLong countAtomic = new AtomicLong(0);
    static LongAdder countLongAdder = new LongAdder();
    static long countLong = 0L;

    public static void main(String[] args) throws InterruptedException {
        Thread[] threads = new Thread[1000];

        for (int i = 0; i <threads.length; i++)
            threads[i] = (new Thread(()->{
                                        for (int n = 0; n < 100_000; n++)
                                            countAtomic.incrementAndGet();
                                    },
                    "t - "+i)
            );
        long s = System.currentTimeMillis();

        for (Thread t : threads) t.start();

        for (Thread t : threads) t.join();

        long e = System.currentTimeMillis();

        System.out.println("countAtomic:"+countAtomic.get()+"time："+(e-s));


        /////////////////////////////////////////////////////
        Object lock = new Object();
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(()->{
                for (int j = 0; j < 100_000; j++) {
                    synchronized (lock) {
                        countLong ++;
                    }
                }
            });
        }

        s = System.currentTimeMillis();

        for (Thread t : threads) t.start();

        for (Thread t : threads) t.join();

        e = System.currentTimeMillis();

        System.out.println("countLong:"+countLong+"time："+(e-s));

        /////////////////////////////////////////////////////



        /////////////////////////////////////////////////////
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(()->{
                for (int j = 0; j < 100_000; j++) countLongAdder.increment();
            });
        }

        s = System.currentTimeMillis();

        for (Thread t : threads) t.start();

        for (Thread t : threads) t.join();

        e = System.currentTimeMillis();

        System.out.println("countLongAdder:"+countLongAdder.intValue()+"time："+(e-s));

        /////////////////////////////////////////////////////



    }

}
